﻿using Company.Core.IOC;
using Company.Logger;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Company.Core.Helpers
{
    public static class JsonHelper
    {
        // indented 表示缩进，保持可读。默认压缩不可读
        public static string ToJson(object obj, bool indented = false)
        {
            var setting = new JsonSerializerSettings();
            setting.NullValueHandling = NullValueHandling.Ignore;
            ////setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            setting.Formatting = indented ? Formatting.Indented : Formatting.None;
            return JsonConvert.SerializeObject(obj, setting);
        }

        public static T ToObject<T>(string json)
        {
            var setting = new JsonSerializerSettings();
            setting.NullValueHandling = NullValueHandling.Ignore;
            return JsonConvert.DeserializeObject<T>(json, setting);
        }

        public static string GetValue(string Key, string Json)
        {
            JObject obj = JObject.Parse(Json);
            return obj[Key].Value<string>();
        }

        public static T LoadFile<T>(string filename)
        {
            if (!File.Exists(filename))
            {
                return default;
            }

            var content = File.ReadAllText(filename);
            return ToObject<T>(content);
        }

        public static void SaveFile(string filename, object obj, bool indented = false)
        {
            var content = ToJson(obj, indented);
            File.WriteAllText(filename, content);
        }
    }
}
